﻿namespace EMall.Query
{
    public class TreeBuilder
    {
        public static TTree Build<TTree, TKey>(IEnumerable<TTree> source, TKey parentId)
            where TTree : class, ITree<TTree, TKey>
        {
            var root = source.FirstOrDefault(o => o.Id.Equals(parentId)) ?? Activator.CreateInstance(typeof(TTree)) as TTree;
            root.Children = GetChildren(source, parentId);
            return root;
        }
        public static IEnumerable<TTree> GetChildren<TTree, TKey>(IEnumerable<TTree> source, TKey parentId)
            where TTree : class, ITree<TTree, TKey>
        {
            var children = source.Where(o => o.ParentId!.Equals(parentId));
            if (children != null)
            {
                foreach (var child in children)
                {
                    child.Children = GetChildren(source, child.Id);
                }
            }
            return children;
        }
    }
}
